package com.yumeko.springcloud.lib;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: SpringCloud
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-08 21:09
 */
@Component
@Slf4j
public class LoadbalancedImpl implements Loadbalanced {
    private AtomicInteger atomicInteger = new AtomicInteger(0);
    private final int getAndcrement(){
        int current,next;
        do{
            current = this.atomicInteger.get();
            next = current >= 2147483647?0:current+1;
        }while (!atomicInteger.compareAndSet(current,next));
        log.info("=======当前next======="+next);
        return next;
    }
    @Override
    public ServiceInstance instance(List<ServiceInstance> instanceList) {
        int index = getAndcrement() % instanceList.size();
        return instanceList.get(index);
    }
}
